package com.example.viewpager;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;

public class ViewPagerAdapter extends PagerAdapter{
	List<String> list;
	Context context;
	LayoutInflater inflater;
	ViewHolder holder;
	showPicHandler handler;
	public ViewPagerAdapter(Context ctx, List<String> _list) {
		this.context = ctx;
		this.list = _list;
		inflater = LayoutInflater.from(ctx);
		handler = new showPicHandler();
	}

	@Override
	public int getCount() {
		return list.size();
	}

	@Override
	public boolean isViewFromObject(View arg0, Object arg1) {
		return arg0 ==arg1;
		
	}
	
	@Override
	public Object instantiateItem(View container, int position) {
		View view = loadPic(position);
		((ViewPager)container).addView(view);
		return view;
	}
	
	@Override
	public void destroyItem(View container, int position, Object object) {
		 ((ViewPager)container).removeView((View) object);
	}
	
	class ViewHolder{
		ImageView img;
	}
	
	private View loadPic(int position) {
		final int location = position;
		View view = inflater.inflate(R.layout.view, null, false);
		holder = new ViewHolder();
		holder.img = (ImageView) view.findViewById(R.id.imageview);
		holder.img.setImageResource(R.drawable.ic_launcher);
		new Thread(){
			public void run() {
				getPic( location);
			};
		}.start();
		return view;

	}
	private void getPic(int position) {
		String urlStr = list.get(position);
		Drawable drawable = null;
		try {
			URL url = new URL(urlStr);
			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			if(con.getResponseCode() == 200){
				InputStream is = con.getInputStream();
				Bitmap bitmap = BitmapFactory.decodeStream(is);
				BitmapDrawable bd = new BitmapDrawable(bitmap);  
		        drawable = (Drawable) bd;  
		        Message msg = new Message();
		        msg.obj = drawable;
		        handler.sendMessage(msg);
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	class showPicHandler extends Handler{
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			holder.img.setImageDrawable((Drawable) msg.obj);
		}
	}
	
}
